package com.atguigu.spzx.manager.modules.utils;

import com.atguigu.spzx.common.vo.TreeBaseVo;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * MenuHelper
 * </p>
 *
 * @author flyduck
 * @since 2023/10/25
 */
public class MenuHelper {
    //构建树形结构
    public static <T extends TreeBaseVo> List<T> buildTree(List<T> treeRespBaseVoList) {
        //创建集合封装最终的数据
        List<T> trees = new ArrayList<>();
        for (T treeRespBaseVo : treeRespBaseVoList) {
            //找到递归的入口：parentId = 0
            if (treeRespBaseVo.getParentId() == 0) {
                trees.add(findChildren(treeRespBaseVo,treeRespBaseVoList));
            }
        }
        return trees;
    }

    /**
     * 递归方法：查询某个节点的所有子节点，并加入到children里面
     * @param parent
     * @param treeRespBaseVoList
     * @return
     */
    private static <T extends TreeBaseVo> T findChildren(T parent, List<T> treeRespBaseVoList) {
        //数据初始化
        parent.setChildren(new ArrayList<>());

        //遍历
        for (T child : treeRespBaseVoList) {
            if (parent.getId().equals(child.getParentId())) {
                parent.getChildren().add(findChildren(child, treeRespBaseVoList));
            }
        }

        return parent;
    }
}
